// pages/honourList/honourList.js
let request = require('../../operation/operation.js')
let students = null

let sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: ['星星榜','红花榜'],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    this.getClassStudents()

    wx.getSystemInfo({
      success: function (res) {
        that.setData({          
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
    * 单击tab事件处理函数
    */
  tabClick: function (e) {
    this.switchTabView(e.currentTarget.id)

    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    })
  },

  switchTabView: function (acticeIndex) {
    let tmpStudents = null
    if ('0' == acticeIndex) {
      tmpStudents = this.sortData(students, 'pointCount')
    } else if ('1' == acticeIndex) {
      tmpStudents = this.sortData(students, 'flowerCount')
    }
    
    this.setData({
      students: tmpStudents
    })
  },
  getClassStudents: function () {
    let that = this
    request.getRequest('/students?klassSid=' + getApp().globalData.param.sid, {}, true)
      .then(res => {
        var data = res.data;
        if (request.SUCCESSED == data.status) {
          students = data.items
          that.setData({
            students: that.sortData(data.items,'pointCount')
          })
        } else {
          wx.showToast({
            title: data.msg,
            iocn: 'none'
          })
        }
      })
      .catch(e => {
        console.log(e)
      })
  },

  sortData:function(students,prop) {
    let result = students.sort(this.compare(prop))
    return result
  },

  compare:function(prop) {    
      return function (obj1, obj2) {
        var val1 = obj1[prop];
        var val2 = obj2[prop]; if (val1 < val2) {
          return 1;
        } else if (val1 > val2) {
          return -1;
        } else {
          return 0;
        }
      }
  }
})